$(function(){
    ko.bindingHandlers.jqSelectableList = {
        init: function(element, valueAccessor, allBindingsAccessor){
            var options = kjq.utils.getOptions(allBindingsAccessor);
            if(!valueAccessor().list){
                throw 'Items array("list" options) for jqSelectableList is undefined.';
            }
            if(!valueAccessor().result){
                throw 'Items array("result" options) for jqSelectableList is undefined.';
            }
            var list = valueAccessor().list;
            var selectedItems = valueAccessor().result;
            var selectableListId = kjq.utils.getRandomElementId();
            var content = '<ul id="'.concat(selectableListId,'" class="kjq-selectable-list">');            
            
            for(var x=0;x<list().length;x++){
                var listElement = '<li class="ui-state-default kjq-selectable-list ui-widget-content">'.concat(list()[x].toString(),'</li>');
                content = content.concat(listElement);
            }
            content.concat('</ul>');
            content = $(content);
            $(element).append(content);
            
            options.stop = function(event, ui){
                selectedItems.removeAll();
                $(".ui-selected", this).each(function(){
                    var index = $("#".concat(selectableListId," li")).index(this);
                    selectedItems().push(list()[index]);
                });
            };
            
            $('#'.concat(selectableListId)).selectable(options);
        }  
    };
});